package com.zanfeng.signleplatform.common.utils;

import com.zanfeng.signleplatform.common.cloud.HttpRespons;
import com.zanfeng.signleplatform.common.cloud.net.HttpRequester;
import org.apache.commons.lang3.ObjectUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Tibers on 16/6/2.
 * 阿里大鱼短信发送
 */
public class SMSUtil {

    private static final String USERNAME = "";
    private static final String PASSWORD = "";
    private static final String LONGNUM = "";
    private static final String SIGN_NAME = "您的验证码是：";
    private static final String REQUEST_URL = "http://101.200.228.238/NewSmsPort/default.asmx/SendSms";

    private static void send(String mobile, String templateCode) throws RuntimeException {
        HttpRequester httpRequester = new HttpRequester();
        Map<String, String> map = new HashMap<>();
        map.put("username", USERNAME);
        map.put("password", PASSWORD);
        map.put("phonelist", mobile);
        map.put("longnum", LONGNUM);
        map.put("msg", SIGN_NAME + templateCode);
        HttpRespons httpRespons = null;
        try {

            httpRespons = httpRequester.sendPost(REQUEST_URL, map);
        } catch (Exception e) {
            throw new RuntimeException("短信发送失败");
        }

        if (httpRespons.getCode() == 200) {
            String regEx = "(-\\w+|\\w+)(\\|)(\\d+)";
            // 编译正则表达式
            Pattern pattern = Pattern.compile(regEx);
            // 忽略大小写的写法
            // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(httpRespons.getContent());
            // 查找字符串中是否有匹配正则表达式的字符/字符串
            boolean rs = matcher.find();
            if (!rs || ObjectUtils.notEqual(matcher.group(1), "1")) {
                throw new RuntimeException("短信发送失败");
            }
        } else {
            throw new RuntimeException("短信发送失败");
        }

    }

    public static void sendAuthCode(String mobile, String code) throws RuntimeException {
        send(mobile, code);
    }


}
